var http = require('http')
var fs = require('fs')
var path = require('path')
var mime = require('mime')
var cache = {}//缓存池

function send404(res){
	res.writeHead(404,{'Content-Type':'text/plain'})
	res.write('404')
	res.end()
}
function sendFile(res,filePath,fileContents){
	res.writeHead(200,{'Content-Type':mime.lookup(path.basename(filePath))})
	res.write(fileContents)
	res.end()
}
function serveStatic(res,cache,absPath){
	if(cache[absPath]&&false){
		sendFile(res,absPath,cache[absPath])
	} else{
		fs.exists(absPath,function(exists){
			if(exists){
				fs.readFile(absPath,function(err,data){
					if(err){
						send404(res)
					} else{
						cache[absPath] = data
						sendFile(res,absPath,cache[absPath])
					}
				})
			} else {
				send404(res)
			}
		})
	}
}

var server = http.createServer(headle)
function headle(req,res){
	var filePath = './dest';//默认路径
	if(req.url == '/'){
		filePath = filePath +'/index.html'
	} else {
		filePath = filePath + req.url;
	}
	serveStatic(res,cache,filePath)
}
server.listen(80)
var socketIo = require('./lib/chat_server');
socketIo.listen(server)
console.log('server started port 80')